package service;

import bean.User;
import dao.UserDao;
import exception.ListProductException;

import javax.security.auth.login.LoginException;
import java.sql.SQLException;
import java.util.List;

public class UserService {
    UserDao dao = new UserDao();
    // 登录操作
    public User login(String username, String password) throws LoginException {
        try {
            //根据登录时表单输入的用户名和密码，查找用户
            User user = dao.findUserByUsernameAndPassword(username, password);
            //如果找到，还需要确定用户是否为激活用户
            if (user != null) {
                return user;
            }
            throw new LoginException("用户名或密码错误");
        } catch (SQLException e) {
            e.printStackTrace();
            throw new LoginException("登录失败");
        }
    }

    // 查找所有学生信息
    public List<User> listAll() throws ListProductException {
        try {
            return dao.listAll();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new ListProductException("查询学生信息失败");
        }
    }

    //添加学生信息
    public void addUser(User user) {
        try {
            dao.add(user);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //根据id查询学生信息
    public User findUserById(String id) throws ListProductException{
        try {
//            User user = dao.findById(Integer.parseInt(id));
            return dao.findById(id);
//            return user;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new ListProductException("查询失败");
        }

    }
    //修改学生信息
    public void updateUser(User user) {
        try {
            dao.updateuser(user);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //根据id删除学生信息
    public void deleteUser(String id) {
        try {
            dao.delete(id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    //多条件查询
    public List<User> findUserByManyCondition(String id, String name, String category, String username) {
        List<User> user = null;
        try {
            user = dao.findUserByManyCondition(id, name, category, username);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }
    //多选删除
    public void delSelectedUser(String[] ids) {
        if(ids != null && ids.length > 0){
            //1.遍历数组
            for (String id : ids) {
                try {//2.调用dao删除
                    dao.delete(id);
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
